﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text; 
using OpenFlashChart;

public partial class data : System.Web.UI.Page
{
    public QualifyRounds LoadData(int Pk_Tournament, out int BestPlayerNumber, out int PlayerLimitToQualify)
    {
        Tournament oTournament = new Tournament(Pk_Tournament);
        int Rondas = oTournament.QualifyRounds;
        QualifyRounds oQualifyRounds = new QualifyRounds(Pk_Tournament);
        int[] Scores = (int[])Session["QualifyScores"];
          
        List<QualifyRound> RoundsWithScore = oQualifyRounds.GetQualifyRoundByPlayerWithScore();
        //Calculamos los puntos

        RoundsWithScore.Sort(new ObjectComparer<QualifyRound>("Machine_Number ASC, Score DESC", true));
        List<Player> oPlayers = new List<Player>(); //Donde almacenamos el total;
        if (RoundsWithScore.Count > 0)
        { //Si hay puntuaciones
            int CalculatingMachineFlag;//controla el cambio de máquina
            int CurrentMachineFlag;//controla el cambio de máquina
            int ScoreCounter = 0; // puntero a la puntuación
            CalculatingMachineFlag = RoundsWithScore[0].Machine_Number;

            //Calculamos los puntos por maquina y hacemos sumatorio

            for (int x = 0; x < RoundsWithScore.Count; x++)
            {
                CurrentMachineFlag = RoundsWithScore[x].Machine_Number;
                if (CurrentMachineFlag == CalculatingMachineFlag)
                {
                    RoundsWithScore[x].PositionInRound = ScoreCounter + 1;

                    if (ScoreCounter < Scores.Length)
                    {  //si le toca puntuación
                        RoundsWithScore[x].PointsInRound = Scores[ScoreCounter];
                        if (x > 0 && RoundsWithScore[x - 1].Score != RoundsWithScore[x].Score)
                        {//Verificamos si no es igual a la posicion anterior
                            ScoreCounter++;
                        }
                        else if (x == 0)
                        {
                            ScoreCounter++;
                        }
                    }
                    else
                    {
                        RoundsWithScore[x].PointsInRound = 0;
                        ScoreCounter++;
                    }

                }
                else
                { //Cambiamos de máquina
                    ScoreCounter = 0;
                    RoundsWithScore[x].PointsInRound = Scores[ScoreCounter];
                    RoundsWithScore[x].PositionInRound = ScoreCounter + 1;
                    ScoreCounter++;
                    CalculatingMachineFlag = RoundsWithScore[x].Machine_Number;

                }
            }


            int CalculatingPlayerFlag;//controla el cambio de máquina
            int CurrentPlayerFlag;//controla el cambio de máquina
            RoundsWithScore.Sort(new ObjectComparer<QualifyRound>("PlayerNumber ASC", true));

            CalculatingPlayerFlag = RoundsWithScore[0].PlayerNumber;
            Player oPlayer = new Player(RoundsWithScore[0].PlayerNumber, 0);
            oPlayers.Add(oPlayer);
            //Calculamos los puntos por maquina y hacemos sumatorio
            for (int x = 0; x < RoundsWithScore.Count; x++)
            {
                CurrentPlayerFlag = RoundsWithScore[x].PlayerNumber;
                if (CurrentPlayerFlag == CalculatingPlayerFlag)
                {
                    oPlayers[oPlayers.Count - 1].PlayerScore += RoundsWithScore[x].PointsInRound;
                }
                else
                { //Cambiamos de máquina

                    CalculatingPlayerFlag = RoundsWithScore[x].PlayerNumber;
                    oPlayer = new Player(RoundsWithScore[x].PlayerNumber, 0);
                    oPlayers.Add(oPlayer);
                    oPlayers[oPlayers.Count - 1].PlayerScore += RoundsWithScore[x].PointsInRound;
                }
            }

        }
        RoundsWithScore.Sort(new ObjectComparer<QualifyRound>("PlayerNumber ASC, Round_Number ASC", true));
        oPlayers.Sort(new ObjectComparer<Player>("PlayerScore DESC", true));
        BestPlayerNumber = oPlayers[0].Player_Number; 
        //Vemos si hay suficientes
        if (oPlayers.Count > oTournament.QualifyPlayersToPlayOffs)
        {
            PlayerLimitToQualify = oPlayers[oTournament.QualifyPlayersToPlayOffs-1].Player_Number;
        }
        else {
            PlayerLimitToQualify = -1;
        }
       
        QualifyRounds oRounds = new QualifyRounds(RoundsWithScore);
        return oRounds;

        

    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.CacheControl = "no-cache";  
        Graph graph = new Graph();
        graph.AxisColorYRight = "#000000";
        OpenFlashChart.Charts.ChartData temp;
        OpenFlashChart.Charts.ChartData leader;
        OpenFlashChart.Charts.ChartData qualify;
        //graph.AxisColorYRight = "#000000";
        try
        {
            if(Request.QueryString["id"]!=null){
                int Player = Int16.Parse(HttpUtility.HtmlDecode(Request.QueryString["id"]).Split('|')[0]);
                int BestPLayer;
                int LimitQualifyPlayer;
                QualifyRounds oQualifyRounds = LoadData(int.Parse(HttpUtility.HtmlDecode(Request.QueryString["id"]).Split('|')[2]), out BestPLayer, out LimitQualifyPlayer);

                        
                List<QualifyRound> RoundsCurrentPlayer = oQualifyRounds.GetQualifyRoundByPlayer(Player);
                List<QualifyRound> RoundsBestPlayer = oQualifyRounds.GetQualifyRoundByPlayer(BestPLayer); //Están ordenadas el 0 es el mejor jugador
                List<QualifyRound> RoundsLimitQualifyPlayer = new List<QualifyRound>();
                if (LimitQualifyPlayer != -1)
                {
                    RoundsLimitQualifyPlayer = oQualifyRounds.GetQualifyRoundByPlayer(LimitQualifyPlayer); //Están ordenadas el 0 es el mejor jugador
                }
                switch (HttpUtility.HtmlDecode(Request.QueryString["id"]).Split('|')[1])
                {
                    case "1":

                        graph.LegendX = new LegendX("Maquinas", 12, "#000000");
                        graph.LegendY = new LegendY("Puntos", 12, "#000000");
                        graph.StepsY = 11;
                        graph.MaxY = 110;

                        
                                                  
                        temp = new OpenFlashChart.Charts.AreaHollow(2, 3, "#0000CC", 75, "Puntos " + RoundsCurrentPlayer[0].Player_Nick + " (Jugador)", 12, "#AAAAFF");
                        InnerBackground oIner = new InnerBackground("#E3F0FD", "#CBD7E6", 90);
                        

                        foreach (QualifyRound iQualifyRound in RoundsCurrentPlayer)
                        {
                             temp.Data.Add(iQualifyRound.PointsInRound);
                             graph.LabelsX.Add(iQualifyRound.Machine_Acron);
                        
                        }
                        
                        graph.Data.Add(temp);

                        leader = new OpenFlashChart.Charts.AreaHollow(2, 3, "#009a0e", 0, "Puntos " + RoundsBestPlayer[0].Player_Nick + " (Lider clasificación)", 12, "#ffffff");

                        foreach (QualifyRound iQualifyRound in RoundsBestPlayer)
                        {
                            leader.Data.Add(iQualifyRound.PointsInRound);
                            //graph.LabelsX.Add("Ronda " + iQualifyRound.Round_Number);

                        }
                        graph.Data.Add(leader);

                        if (LimitQualifyPlayer != -1) {
                            //List<QualifyRound> RoundsLimitQualifyPlayer = oQualifyRounds.GetQualifyRoundByPlayer(LimitQualifyPlayer); //Están ordenadas el 0 es el mejor jugador
                            qualify = new OpenFlashChart.Charts.AreaHollow(2, 3, "#ff0000", 0, "Puntos " + RoundsLimitQualifyPlayer[0].Player_Nick + " (Corte playoffs)", 12, "#ffffff");

                            foreach (QualifyRound iQualifyRound in RoundsLimitQualifyPlayer)
                            {
                                qualify.Data.Add(iQualifyRound.PointsInRound);
                                //graph.LabelsX.Add("Ronda " + iQualifyRound.Round_Number);

                            }
                            graph.Data.Add(qualify);
                        }
                      
                        Response.Clear();
                        Response.Write(graph.ToString());
                        break;
                    case "2":
                        graph.LegendX = new LegendX("Total puntos", 12, "#000000");
                        graph.LegendY = new LegendY("Puntos", 12, "#000000");
                        graph.StepsY = 10;
                        graph.MaxY = 650;

                        temp = new OpenFlashChart.Charts.Bar(70, "#0000CC", "Jugador", 12);
                        float sum=0;
                        foreach (QualifyRound iQualifyRound in RoundsCurrentPlayer)
                        {
                            sum += iQualifyRound.PointsInRound;

                        }
                        //graph.LabelsX.Add(RoundsCurrentPlayer[0].Player_Nick);
                        temp.Data.Add(sum);
                        graph.Data.Add(temp);


                        leader = new OpenFlashChart.Charts.Bar(70, "#009a0e", "Lider", 12);

                        if (LimitQualifyPlayer != -1)
                        {
                            sum = 0;
                            qualify = new OpenFlashChart.Charts.Bar(70, "#ff0000", "Corte playoffs", 12);
                            foreach (QualifyRound iQualifyRound in RoundsLimitQualifyPlayer)
                            {
                                sum += iQualifyRound.PointsInRound;

                            }
                            qualify.Data.Add(sum);
                            //graph.LabelsX.Add(RoundsLimitQualifyPlayer[0].Player_Nick);
                            graph.Data.Add(qualify);
                        }

                        sum = 0;
                        foreach (QualifyRound iQualifyRound in RoundsBestPlayer)
                        {
                            sum += iQualifyRound.PointsInRound;

                        }
                        //graph.LabelsX.Add(RoundsBestPlayer[0].Player_Nick);
                        leader.Data.Add(sum);
                        graph.Data.Add(leader);

                       
                       
                        Response.Clear();
                        Response.Write(graph.ToString());
                        break;

                }
            }else{
                Response.Clear();                
                 //Response.End();
            }
        }
        catch (Exception Ex) {
            Response.Write(Ex.Message);
        
        }

        
       
    }
}
